package com.lv.suyiyong.hfrwork.fragment

import android.Manifest
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.blankj.utilcode.util.SizeUtils
import com.google.android.material.imageview.ShapeableImageView
import com.google.gson.reflect.TypeToken
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.base.BaseFragment
import com.lv.common.bean.CustomMessageBean
import com.lv.common.bean.CustomMessageChatBean
import com.lv.common.imp.OnPositionTListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.LogUtil
import com.lv.common.utils.PermissionXUtils
import com.lv.common.utils.PermissionXUtilsCallback
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.adapter.HomeTabAdapter
import com.lv.service.bean.CommonSelectedBean
import com.lv.service.bean.CommonTab
import com.lv.service.event.HomeTabChangeEvent
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.utils.YgxAroutPageKt
import com.lv.suyiyong.hfrwork.R
import com.lv.suyiyong.hfrwork.databinding.FragmentHomeBinding
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMConversation
import com.tencent.imsdk.v2.V2TIMConversationListener
import com.tencent.imsdk.v2.V2TIMConversationResult
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMMessage
import com.tencent.imsdk.v2.V2TIMValueCallback
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.interfaces.TUICallback


/**
 * 作者： ygx
 * 创建日期：2023/2/10 11:24 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：应用商城需要的权限：ABCDEFGHIJKLMNO
 */
class HomeFragment : BaseFragment() {
    private val mBeans = mutableListOf<CommonTab>()
    private val mOnLineBeans = mutableListOf<CommonSelectedBean>()
    private var mAdapter: HomeTabAdapter? = null
    private var mUserInfo: UserInfo? = null
    private var mOnLine = "0"
    private var mIvLogo: ShapeableImageView? = null
    private var mIvMore: ImageView? = null
    private var mTvMessageText: TextView? = null
    private var mTvMsgTotalUnread: TextView? = null
    private var mViewChatBg: View? = null
    private var mBinding: FragmentHomeBinding? = null

    override fun getLayoutRes() = R.layout.fragment_home
    override fun bindView(view: View, savedInstanceState: Bundle?): ViewDataBinding {
        mBinding = FragmentHomeBinding.bind(view).apply {
            mTvMessageText = tvMessageText
            mTvMsgTotalUnread = msgTotalUnread
            mViewChatBg = viewChatBg
            mIvMore = ivMore
            userInfo = mUserInfo
            StatusBarUtil.setHeightAndPadding(requireContext(), tvTitle)

            val gridLayoutManager = GridLayoutManager(requireContext(), 3)
            mAdapter = HomeTabAdapter(mBeans)
            adapter = mAdapter
            rvContent.layoutManager = gridLayoutManager
            rvContent.addItemDecoration(
                SpacesItemDecoration(
                    SizeUtils.dp2px(19.0f),
                    SizeUtils.dp2px(0f),
                    false
                )
            )
//            ivLogo.setOnClickListener {
//                val json = GsonUtils.toJson(mImageBeans)
//                ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
//                    .withInt("position", 0)
//                    .withString("data", json)
//                    .navigation()
//            }
        }

        return mBinding!!
    }

    override fun initConfig() {
        super.initConfig()
        mBinding?.rvContent?.visibility = View.GONE
        mOnLineBeans.clear()
        mOnLineBeans.add(CommonSelectedBean("书刊推广数据", selected = true))
        mOnLineBeans.add(CommonSelectedBean("APP推广数据", selected = false))
        UserDbHelper.getLiveUserInfo(requireContext()).observeKt { userInfo ->
            if (userInfo != null && userInfo.id.isNotEmpty()) {
                mUserInfo = userInfo
                mIvLogo?.LoadSrc(userInfo.image)
                val role = userInfo.role ?: ""
                mBeans.clear()
                mBeans.add(CommonTab("", "", "工作台", 0, true))
                mBeans.add(
                    CommonTab(
                        "0", "j", "客户列表", com.lv.common.R.drawable.icon_kehu, false
                    )
                )
                mAdapter?.notifyDataSetChanged()
                mBinding?.rvContent?.visibility = View.VISIBLE
            } else {
                mUserInfo = null
                mBinding?.rvContent?.visibility = View.GONE
                mIvLogo?.LoadSrc(0)
            }
        }


    }

    override fun initData() {
        super.initData()

         // 1. 设置会话监听
         V2TIMManager.getConversationManager().addConversationListener(v2TIMConversationListener)
         // 2. 先拉取50个本地会话做 UI 展示，nextSeq 第一次拉取传0
         V2TIMManager.getConversationManager().getConversationList(
             0, 50,
             object : V2TIMValueCallback<V2TIMConversationResult?> {
                 override fun onSuccess(v2TIMConversationResult: V2TIMConversationResult?) {
                     val nextSeq = v2TIMConversationResult?.nextSeq
                     LogUtils.e(
                         "imsdk",
                         "success nextSeq:" + nextSeq + ", isFinish:" + v2TIMConversationResult?.isFinished
                     )
                     val v2TIMConversationList = v2TIMConversationResult?.conversationList
                     v2TIMConversationList?.let {
                         refreshHomeRing(v2TIMConversationList)
                     }

                 }

                 override fun onError(code: Int, desc: String) {
                     LogUtils.e("imsdk", "failure, code:$code, desc:$desc")
                 }


             })

    }

    private val v2TIMConversationListener: V2TIMConversationListener =
        object : V2TIMConversationListener() {
            // 3.1 收话新增的回调
            @RequiresApi(api = Build.VERSION_CODES.N)
            override fun onNewConversation(conversationList: List<V2TIMConversation>) {
                super.onNewConversation(conversationList)
                LogUtil.e("onNewConversation", "onNewConversation")
            }

            // 3.2 收到会话更新的回调
            @RequiresApi(api = Build.VERSION_CODES.N)
            override fun onConversationChanged(conversationList: List<V2TIMConversation>) {
                if (conversationList.isEmpty()) {
                    return
                }
                val v2TIMConversation = conversationList[0]
                checkLoginOtherDevice(v2TIMConversation)
                refreshHomeRing(conversationList)

            }
        }
    private val mMessages = mutableListOf<V2TIMConversation>()

    private fun refreshHomeRing(conversationList: List<V2TIMConversation>) {
        for (i in conversationList.indices) {
            val conv = conversationList[i]
            var isExit = false
            for (j in mMessages.indices) {
                val uiConv = mMessages[j]
                // UI 会话列表存在该会话，则替换
                if (uiConv.conversationID == conv.conversationID) {
                    mMessages[j] = conv
                    isExit = true
                    break
                }
            }
            // UI 会话列表没有该会话，则新增
            if (!isExit) {
                mMessages.add(conv)
            }
        }
        val messages = mutableListOf<V2TIMConversation>()
        mMessages.let {
            it.forEach { item ->
                val unreadCount = item.unreadCount
                if (unreadCount > 0) {
                    messages.add(item)
                }
            }
        }

        if (messages.isNotEmpty()) {
            messages.sortByDescending { item -> item.lastMessage.timestamp }
            val v2TIMConversation = messages[0]
            var conversationID = v2TIMConversation.conversationID
            val unreadCount = v2TIMConversation.unreadCount
            mTvMsgTotalUnread?.text = "$unreadCount"
            mIvMore?.visibility = if (unreadCount > 0) View.VISIBLE else View.GONE
            mTvMsgTotalUnread?.visibility = if (unreadCount > 0) View.VISIBLE else View.GONE
            if (conversationID.startsWith("c2c_")) {
                conversationID = conversationID.drop(4)
            }
            if (conversationID.contains("syy0000")) {
                val customText = v2TIMConversation.lastMessage.customElem
//                var dataCustom = customText ?: return
                if (customText == null) {
                    initChatMessage()
                    return
                }
                val customJson = customText.data.toString(Charsets.UTF_8)
                val jsonType = object : TypeToken<CustomMessageChatBean?>() {}.type
                val jt: CustomMessageChatBean = GsonUtils.fromJson(customJson, jsonType)
//                val t = jt.t
//                val ti = jt.ti
//                val tt = jt.tt
//                val sender = jt.sender
                if (activity != null) {
                    YgxAroutPageKt.aroutPager(requireContext(), jt, mViewChatBg)
                }

                when (conversationID) {

                    Constants.SYY_YWY_FXXX -> {//风险下线
                        mTvMessageText?.text = "您有新的风险下线消息"
                    }


                    else -> {
                        mTvMessageText?.text = "未知消息"

                    }

                }

            } else {
//                val userID = v2TIMConversation.userID
//                val showName = v2TIMConversation.showName
//                TUIUtils.startChat(userID, showName, V2TIMConversation.V2TIM_C2C)
            }
        } else {
            initChatMessage()
        }
    }

    private fun initChatMessage() {
         mTvMsgTotalUnread?.visibility = View.GONE
         mIvMore?.visibility = View.GONE
         mTvMessageText?.text = "消息通知"
         mViewChatBg?.setOnClickListener {
             //跳转到消息Tab
             LiveEventBus
                 .get(HomeTabChangeEvent::class.java)
                 .post(HomeTabChangeEvent("", 2))
         }
     }

     private fun checkLoginOtherDevice(v2TIMConversation: V2TIMConversation) {
         val chatTag = SPStaticUtils.getString(Constants.KEY_CHAT_TOKEN, "aaa")
         val userID = v2TIMConversation.userID
         if (mUserInfo?.txaccid == userID) {
             val customText = v2TIMConversation.lastMessage.customElem
             val customJson = customText.data.toString(Charsets.UTF_8)
             val jsonType = object : TypeToken<CustomMessageBean?>() {}.type
             val jt: CustomMessageBean = GsonUtils.fromJson(customJson, jsonType)
             val idSyyAccid = jt.id_syy_accid
             if (idSyyAccid.isEmpty() || !idSyyAccid.contains("速易甬")) {
                 return
             }
             val split = idSyyAccid.split("速易甬".toRegex()).toTypedArray()
             if (split.size < 3) {
                 return
             }
             if (mUserInfo?.txaccid != split[1]) {
                 return
             }
             if (mUserInfo?.phone != split[2]) {
                 return
             }
             if (!TextUtils.isEmpty(chatTag) && chatTag != "aaa" && split[0] != chatTag) {
                 TUILogin.logout(object : TUICallback() {
                     override fun onSuccess() {
                         YgxUtilsKt.setAppToken("", "", "")
                         V2TIMManager.getConversationManager()
                             .removeConversationListener(null)
                         ARouter.getInstance().build(ARoutUtils.LoginOutActivity).navigation()

 //                        showLoginOutDialog()
                     }

                     override fun onError(errorCode: Int, errorMessage: String?) {
                     }
                 })

             }
         } else {
         }
     }


    override fun initEvents() {
        super.initEvents()
        mAdapter?.onViewItemClickListener = OnPositionTListener { position, data ->
            if (!data.isNullOrEmpty()) {
                when (data) {
                    "j" -> {//亨富然
                        ARouter.getInstance()
                            .build(ARoutUtils.ClientsHFRActivity).navigation()
                    }
                }
            }

        }
        addToBlackList()
//        rigestEventBus()
    }



    private fun addToBlackList() {
        // 设置在线和离线都不接收消息
        val userList: MutableList<String> = ArrayList()
        userList.add(Constants.ID_FW_OLD)
        userList.add(Constants.ID_HD_OLD)
        userList.add(Constants.ID_TZ_OLD)

        V2TIMManager.getMessageManager().setC2CReceiveMessageOpt(
            userList,
            V2TIMMessage.V2TIM_NOT_RECEIVE_MESSAGE,
            object : V2TIMCallback {
                override fun onSuccess() {
                    LogUtils.e("imsdk", "success")
                }

                override fun onError(code: Int, desc: String) {
                    LogUtils.e("imsdk", "failure, code:$code, desc:$desc")
                }
            })

    }

    companion object {
        @JvmStatic
        fun newInstance() = HomeFragment()
    }

    override fun onResume() {
        super.onResume()
        LogUtils.e("onResume")
    }


    override fun onDestroy() {
        super.onDestroy()
    }

//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        if (data != null) {
//            //QQ回调
//            ShareUtils.get().onQqActivityResult(requestCode, resultCode, data)
//        }
//    }
}